package guoran.red.scanner;

import android.content.Context;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.EventChannel;

/** ScannerPlugin */
public class ScannerPlugin implements FlutterPlugin {

  private static final String CHANNEL = "guoran.red.scanner/plugin";
  private EventChannel eventChannel;
  private ScannerBroadcastReceiver receiver;

  @SuppressWarnings("deprecation")
  public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) {
    ScannerPlugin plugin = new ScannerPlugin();
    plugin.setupChannels(registrar.messenger(), registrar.context());
  }

  private void setupChannels(BinaryMessenger messenger, Context context) {
    eventChannel = new EventChannel(messenger, CHANNEL);
    receiver = new ScannerBroadcastReceiver(context);
    eventChannel.setStreamHandler(receiver);
  }

  @Override
  public void onAttachedToEngine(FlutterPluginBinding binding) {
    setupChannels(binding.getBinaryMessenger(), binding.getApplicationContext());
  }

  @Override
  public void onDetachedFromEngine(FlutterPluginBinding binding) {
    teardownChannels();
  }

  private void teardownChannels() {
    eventChannel.setStreamHandler(null);
    receiver.onCancel(null);
    eventChannel = null;
    receiver = null;
  }
}
